<?php require_once("getCommonFilename.php"); ?>
<html>
<head>
<title>Psych</title>

		<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.15.custom.css" rel="stylesheet" />
		<link type="text/css" href="css/miniAudioPlayer.1.2/miniplayer.css" rel="stylesheet" />	
		<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
		<!-- date manipulation -->
		<script type="text/javascript" src="js/date.js"></script>
		<!-- For the GET string in a URL -->
		<script type="text/javascript" src="js/jquery.query-2.1.7.js"></script>
		<!-- jquery-UI for autocomplete, datepicker -->
		<script type="text/javascript" src="js/jquery-ui-1.8.15.custom.min.js"></script>
		<!-- rounded corners -->
		<script type="text/javascript" src="js/jquery.corner.js"></script>
		<!-- audio -->
		<script type="text/javascript" src="js/jquery.metadata.js"></script>
		<script type="text/javascript" src="js/jquery.jplayer.min.js"></script>
		<script type="text/javascript" src="js/jquery.mb.miniPlayer.js"></script>

</head>

<body>

	<style>
	.ui-autocomplete {
		max-height: 100px;
		overflow-y: auto;
		/* prevent horizontal scrollbar */
		overflow-x: hidden;
		/* add padding to account for vertical scrollbar */
		padding-right: 20px;
	}
	</style>

<script type="text/javascript">

$(document).ready(function(){
	
	$("#status").append("Loading data.");

	var commonFilename="<?php global $commonFilename; echo $commonFilename ?>";
	var dataLoadCurrent=0;
	var hasLinkedToGet=false;
	var dataLoadTotal=$(".autopop").length;
	var waitingForPopulate=new Array();
	
	function psychCalc() {
		var sDate=Date.parse($("#startDate").attr('value')).toString("yyyy-MM-dd");
		var eDate="NA";
		if ($("#endDate").attr('value').length>0) {
		   eDate=Date.parse($("#endDate").attr('value')).toString("yyyy-MM-dd");
		}
		$.ajax({url: "getData.php", data:{ shockType: $("#shockType").attr('value'),
							  startDate: sDate,
							  endDate: eDate,
							  state: $("#state").attr('value'),
							  regionType: $("#regionType").attr('value'),
							  regionName: $("#regionName").attr('value'),
							  measurementType: $("#measurementType").attr('value'),
							  metric: $("#metric").attr('value')
							 },
				success: function(gdMessage) {
							  var gdMessages = gdMessage.split('|');
					  		  $("#status").html(gdMessages[0]);	
				},
				async:false	    
    		});
  		$.get("processData.html",{filename: commonFilename}, function(message) {
									  var messages = message.split('|');
  							  		  $("#status").append(messages[0]);
									   refreshGraphSrcs(messages);
									  $("#tblGraphs,.outputText").show();
									  $("#firstDisclaimer").hide();
									  if (messages[1]=="XX") {
									    $("#explanation").html("Sadly, you don't have enough data to analyze.<br/> Future versions will hopefully tell you which data you need.");
									  } else {
  									    $("#explanation").html("Disclaimer: Psych is one of many ways to look at the data. With that said, and kept in mind,<br/> Psych reports: ");
										var posneg=(messages[1].substr(0,1)=="-") ? "negative" : "positive";
  									    $("#explanation").append(" an effect of " + messages[1] + " " +
										chanceStr(messages[2].trim(),posneg));
									  }
  							 } 	    
      		); 
	}
	
	function chanceStr(probStr,posneg) {
			 var prob=parseFloat(probStr);
			 var str="";
			 if(prob<.6) {
			 	str="and it's highly uncertain if the effect exists at all.";
			 } else if (prob<.84) {
			 	str="but it's possible that this effect is a result of randomness";
			 } else if (prob<.95) {
			 	str="and there's a fair chance that the effect is " + posneg +".";
			 } else if (prob<.99) {
			 	str="and there's a good chance that the effect is " + posneg +".";
			 } else if (prob<=1) {
			 	str="and there's a very good chance that the effect is " + posneg +".";
			 } else {
 			   str="[error with string " + probStr + "].";
			 }
			 return(str);
	}  
	
	function populateTag(fieldName) {
	  var constraint1Val="";
	  if (fieldName=="regionName") {
	     //alert($("#regionType").attr('value'));
	  	 if ($("#regionType").attr('value').length>0) {
	  	    constraint1Val=$("#regionType").attr('value');
		 }
	  }
	  waitingForPopulate[fieldName]=true;
      $.ajax({url: "getFieldListing.php", data: {field: fieldName, constraint1: constraint1Val}, success: function(listing) { 	    
 		$( "#" + fieldName ).autocomplete({
  			source: listing.split("|"),
			minLength: 0,
			delay: 0,
			select: function(event, ui) {$( "#" + fieldName ).val(ui.item.value); updateEntry(fieldName);}
  		});
  	    waitingForPopulate[fieldName]=false;
		dataLoadSuccess();			  
  	  }, async: false});

	}
	
	function refreshGraphSrcs(messages) {
		var i=0;
    	$(".outGraph").each(function() {
    	    var namePart=this.id;
    		namePart=namePart.substring(5).toLowerCase();
			var timestamp = new Date().getTime();
    	    $(this).attr("src","dataR/" + namePart + commonFilename + ".jpg" + '?' +timestamp );
    	    $(this).attr("title","Details: " + messages[3+i]);
			i=i+1;
    	 }
    	);
	
	}
	
	/*for linking to a psych */
	function linkToGet() {
		$(".autopop, .datepick").each(function() {
		    $(this).val($.query.get($(this).attr('id')));
			updateEntry($(this).attr('id'));
		});
	}
	
	/* I count up how many AJAX queries I conduct.
	 * If equal to the total number of input fields, I've loaded the data.
	 * After the initial load, I can reset dataLoadTotal to track
	 *  additional loading.
	*/
	function dataLoadSuccess() {
		dataLoadCurrent++;
		if (dataLoadCurrent==dataLoadTotal) {
			$("#status").html("Data loaded.");
			if(!hasLinkedToGet) {
			   linkToGet();
			   hasLinkedToGet=true;
			}
		} else if (dataLoadCurrent<dataLoadTotal) {
			$("#status").append(".");
		}
	}

	var fullWidth=800;
	/*The title bar with logo and tool description*/
	$("#titlebar").css({'width':fullWidth});
	$(".topBarText").css({'text-align':'center','font-family':'sans-serif','font-weight':'bold'});
	
	/*The elevator pitch audio*/
	  $(".audio").mb_miniPlayer({
        width:100,
		skin:'blue',
        inLine:true,
		showRew:true,
		showTime:false,
		mp3:"http://ec2-184-73-101-215.compute-1.amazonaws.com/psych/audio/intro.mp3",
		ogg:"http://ec2-184-73-101-215.compute-1.amazonaws.com/psych/audio/intro.ogg",
		swfPath:"js/"
      });
  	//$("#innerAudioText").css({'font-family':'Verdana','font-size':'30%'});
	$("#allAudio").hide();
	
	
	/*The helper box*/
	$("#helper").css({'font-family':'sans-serif', 'width':fullWidth, 'background':'#444', 'color':'#fff', 'padding':'5px'});
	$("#helper").corner('10px');
	$("#helper").click(function () {nextHint()});
	var hintIndex=-1;
	nextHint();
	
	$("#lastUpdate").css({'font-size':'90%'});
	
	/* Example links
	  Ex1: http://ec2-184-73-101-215.compute-1.amazonaws.com/psych/psych.php?shockType=Story+In+The+Media&startDate=10/01/2011&state=NH&regionType=City&regionName=Keene&measurementType=Mean%20Value&metric=SupportID
	  Ex2: http://ec2-184-73-101-215.compute-1.amazonaws.com/psych/psych.php?shockType=Radio%20Commercial&startDate=10/08/2011&endDate=10/12/2011&state=NH&regionType=Media%20Market&regionName=Burlington&measurementType=Mean+Value&metric=SupportID
	  Ex3: http://ec2-184-73-101-215.compute-1.amazonaws.com/psych/psych.php?shockType=Field+Innovation&startDate=10/15/2011&endDate=10/16/2011&state=NH&regionType=Organizer+Region&regionName=Monadnock&measurementType=Progress+To+Goal&metric=SupportID
	*/
	function nextHint() {
		var hints=new Array();
		hints[0]="  Example 1: On Oct 1, the local Keene newspaper ran a story about your opponent's corruption. How much did the story boost your net support? Did the bounce linger? (Try below and click for the answer.)";
		hints[1]="  Answer 1:  The story does pretty well initially in boosting your support, but it looks like your campaign will have to beat the drum to see long-term effects. (Click for next example.)";
		hints[2]="  Example 2: You just bought a new radio commercial, which aired Oct 8-12 2011, in the Burlington Media Market. Everyone Loved it, but did it have an effect on your mean support? (Try below and click for the answer.)";
		hints[3]="  Answer 2: The radio ad looks to have stopped a slide elsewhere in the state. But, with the ad off the air, the effect appears to be diminishing, though not disappearing. (Click for next example.)";
		hints[4]="  Example 3: Your Monadnock field organizer Joe has some exciting news: his new canvassing technique last weekend (Oct 15-16 2011) boosted the number of 1s he gathered! Did it? (Try below and click for the answer.)";
		hints[5]="  Answer 3: \"It ain't so, Joe.\" While Joe's region consistently performs better than the others, Joe did not perform disporportionately better that weekend. (Click for next example.)";

		hintIndex = (hintIndex+1) % hints.length;

		var backgroundColors=new Array();
		backgroundColors[0]="#444";
		backgroundColors[1]="#660033";
		backgroundColors[2]="#330066";
		var bcIndex=Math.floor(hintIndex/(backgroundColors.length-1));

		$("#helper").css({'background':backgroundColors[bcIndex]});
		$("#helperText").html(hints[hintIndex]);
		
	}

	/*makes text a bit prettier*/
	//$("#entryDiv").css({'line-height':'115%','margin-bottom': '10px'});
	
	/*First Disclaimer*/
	$(".disclaimerOuter").css({'margin': '0px', 'background': 'darkred', 'padding': '8px', 'width': fullWidth });
	$(".disclaimerInner").css({ 'margin': 0, 'background': '#FFFFFF', 'padding': '10px', 'border':0, 'zoom':1});
	$(".disclaimerInner").corner("round 8px").parent().css('padding', '4px').corner("round 10px");
	
	/*Psych in text*/
	$(".psychText").css({'font-weight':'bold','color':'darkblue'});
	
	/* create date pickers */
	$(".datepick").each(function() {
		  $(this).datepicker({ showAnim: 'fadeIn', duration: 'slow' });
	  }
	);

	/*Populate boxes */
	$(".autopop").each(function() {
		  $(this).focus(function() {
		    //while(waitingForPopulate[this.id]) {alert("waiting");}
			$(this).autocomplete( "search" , ""  );
		  });
		  populateTag(this.id);
	  }
	);
	
	/*start with "between" rather than "on" */
	if ($("#onOrBetween").attr('value')=="") {
	   $("#onOrBetween").val('between');
	}
	
	/*fanciness -- all the relations between the entry boxes */
	/*Rallies happen on one day*/
	//$("#shockType").change(function () {shockUpdated();});
	function updateEntry(name) {
		if (name=="shockType") {
		   shockUpdated();
		} else if (name=="regionType") {
		   regionTypeUpdated();
		} else if (name=="onOrBetween") {
		  onOrBetweenUpdated();
		}
	}
	
	function onOrBetweenUpdated() {
		var oob=$("#onOrBetween").attr('value');
	    if (oob=="on") {
		   $(".endDateField").hide();
		   $("#endDate").val('');
		} else {
		   $(".endDateField").show();
		}	
	}
	
	function shockUpdated() {

		var shockType=$("#shockType").attr('value');
		if (shockType=="Rally" || shockType=="Story In The Media") {
		   showOneDate(true);		   
		} else {
		   showOneDate(false);
		}
	}
	
	function showOneDate(oneDate) {
		$("#onOrBetween").val(oneDate ? "on" : "between");
		updateEntry("onOrBetween");
	}
	
	function regionTypeUpdated() {
		populateTag("regionName");
		if($("#regionName").attr('value').length>0) {
		  $("#regionName").val('');
		}
	}

	/*button*/
	$("#calc").button();
	$("#calc").click(psychCalc);
	
	/*hide results, for now */
	$("#tblGraphs,.outputText").hide();
	
	/*how it works*/
	$("#howWorksOuter").hide();
	$("#howWorksOuter").css({'margin': '0px', 'background': 'darkblue', 'padding': '8px', 'width': fullWidth });
	$("#howWorksInner").css({ 'margin': 0, 'background': '#FFFFFF', 'padding': '10px', 'border':0, 'zoom':1});
	$("#howWorksInner").corner("round 6px").parent().css('padding', '3px').corner("round 10px");
	$("#howWorksTable").css({'width': fullWidth });
	$(".howWorksLink").click(function () {

	   if ($("#howWorksOuter").is(':visible')) {
	   	  $("#howWorksOuter").hide();
	   } else {
	   	  $("#howWorksOuter").show();
	   }
	});
	refreshGraphSrcs();
 });


</script>

<div id="titlebar">
<table><tr>
  <td width="20%"><img width="200px" height="70px" src="logo.png" /></td>
  <td width="55%" align="center"><span id="allAudio"><span class="topBarText">1-min intro:</span><a id="elevator" class="audio">Intro</a></span></td><td id="toolDescription" class="topBarText">A new tool for<br/>Democratic Data</td></tr></table>
</div>
<br/>
<div id="helper">
  <span id="helperText">
  </span>
</div>
<br/>
<div class="ui-widget">
	<table id="entryTable" class="ui-widget">
	<tr><td>I would like to know the effect of the <input id="shockType" class="autopop" size="23"></td></tr>
	<tr><td>that took place <input id="onOrBetween" class="autopop" size="12"> <input id="startDate" type="text" class="datepick"> <label for="endDate" class="endDateField">and </label><input id="endDate" type="text" class="datepick endDateField"></td></tr>
	<tr><td>in the state of <input id="state" class="autopop" size="2">, in the <input id="regionType" class="autopop" size="20"> of <input id="regionName" class="autopop" size="20"></td></tr>
	<tr><td>on the <input id="measurementType" class="autopop" size="20"> of <input id="metric" class="autopop" size="20"> in that area.</td></tr>
	</table>
	<input type="submit" id="calc" value="Please tell me">&nbsp;&nbsp;&nbsp;<a class="howWorksLink" href="#">How it works</a><br/><br/>
	<div id="howWorksOuter"><div id="howWorksInner"><table id="howWorksTable"><tr width="100%">
	<td width="90%"><span class="psychText">Pysch</span> works by examining the information in your database (usually, field information, such as ID calls or volunteer tags). Here are some things to keep in mind.<br/>
	<ul>
	<li><b><span class="psychText">Pysch</span> compares geographic areas.</b> If a story breaks in a local paper, <span class="psychText">Pysch</span> assumes that the story's impact will occur disproportionately in that paper's geographic area.
	<span class="psychText">Pysch</span> relies on this disparity of impacts to determine the effect size. 
	<li><b><span class="psychText">Pysch</span> compares before and after.</b> In the local story example, <span class="psychText">Pysch</span> assumes that the effect of the story will be the largest in the day the story breaks and immediately afterwards.
	<span class="psychText">Pysch</span> uses the time before the story hits as a reference period to compare against.
	<li><b><span class="psychText">Pysch</span> should compare apples to apples.</b> If <span class="psychText">Pysch</span> is evaluating the effect of campaign events on support ID responses,
	it's best to restrict <span class="psychText">Pysch</span> to viewing only certain types of ID gathering that remain relatively constant over the course of the campaign--i.e., nightly volunteer phone bank, robosurvey. This would be done on the back-end and not visible to the user.
	<li><b><span class="psychText">Pysch</span> is <i>not</i> a randomized experiment</b>, and is less reliable than randomized experiments. Use <span class="psychText">Pysch</span> when randomized experiments are unavailable.
	<li><b>Effect size meanings.</b> For "average value," <span class="psychText">Pysch</span> indicates the average effect on (usually) the 5-point support ID scale.
	For "progress to goal," <span class="psychText">Pysch</span> indicates the percentage point boost in the daily percent of the goal achieved; if you normally knock off 10% of your goal each day and <span class="psychText">Pysch</span> reports a positive effect of 3%,
	 then you would expect to start achieving 13% of your goal each day.    
	</ul>
	</td><td width="10%" valign="top" align="center"><a class="howWorksLink" href="#">X</a></td></tr></table></div></div>
	<table id="tblGraphs"><tr><th>Overall Effect</th><th>Before-After View</th><th>Effect Over Time</th></tr>
	<tr><td><img id="graphOverall" class="outGraph"/></td><td><img id="graphDetail" class="outGraph"/></td><td><img id="graphTime" class="outGraph"/></td></tr></table>
	<div id="explanation" class="outputText"></div> 
</div>
<br/>
Status: <span id="status"></span>
<br/>
<br/>
<div id="firstDisclaimer" class="disclaimerOuter"><div class="disclaimerInner">
<span class="psychText">Pysch</span> is one way to look at data; randomized experiments, experience, and common sense should always inform your campaign.
</div></div>
<br/>
<br/>
<div id="lastUpdate">Last Updated: October 18 2011. Currently in Early Beta and active development. Suggestions welcome: aaron.b.strauss (AT) gmail.<br/>
Also, please remember that this data is very fabricated, so it may not act as you would normally expect.</div>
</body>
</html>
